package com.skyable.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.skyable.common.common.ResponseResult;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.constants.exception.DeviceExcpConstants;
import com.skyable.common.utils.ParamUtil;
import com.skyable.device.config.CloudApplicationContext;
import com.skyable.device.entity.ProductInfo;
import com.skyable.device.feign.ServerFeignApi;
import com.skyable.device.service.IProductInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author GaoYuan
 * @title: ProductInfoController
 * @projectName private-cloud
 * @description: TODO
 * @date 2021/7/312:09
 */
@Slf4j
@Api(value = "产品管理")
@RestController
@RequestMapping("product")
public class ProductInfoController extends BaseController {

    @Autowired
    private ServerFeignApi serverFeignApi;
    @Autowired
    private IProductInfoService productInfoService;

    /**
     * 查询主域产品列表（不分页）
     * @param productInfo
     * @return
     */
    @ApiOperation(value = "查询主域产品列表")
    @PostMapping(value = "/view")
    public ResponseResult listProduct(@RequestBody ProductInfo productInfo) {
        if(productInfo == null) {
            productInfo = new ProductInfo();
        }
        productInfo.setDomainId(CloudApplicationContext.domainId.get());
        ServiceResult<List<ProductInfo>> serviceResult = productInfoService.getProductList(productInfo);
        if (!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(), serviceResult.getMessage());
        }
        List<ProductInfo> productInfoList = serviceResult.getResult();
        return ResponseResult.success(productInfoList);
    }

    /**
     * 获取产品列表
     * @param productInfo
     * @param limit
     * @param page
     * @return
     */
    @ApiOperation(value = "分页查询产品列表")
    @PostMapping(value = "/view/{page}/{limit}")
    public ResponseResult listProductByPage(@RequestBody ProductInfo productInfo,
                                      @PathVariable("limit")Integer limit,
                                      @PathVariable("page")Integer page) {
        productInfo.setDomainId(CloudApplicationContext.domainId.get());
        ServiceResult<IPage<ProductInfo>> serviceResult = productInfoService.getProductList(productInfo, page, limit);
        if (!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(), serviceResult.getMessage());
        }
        IPage<ProductInfo> productInfoIPage = serviceResult.getResult();
        List<ProductInfo> productInfoList = productInfoIPage.getRecords();
        return ResponseResult.success(productInfoList);
    }

    /**
     * 根据ID获取产品信息
     * @param productId
     * @return
     */
    @ApiOperation(value = "查询产品详情")
    @GetMapping(value = "/view/{id}")
    public ResponseResult getProductInfoById(@PathVariable("id") String productId) {
        ServiceResult<ProductInfo> serviceResult = productInfoService.getProductInfoById(productId);
        if (!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(), serviceResult.getMessage());
        }
        return ResponseResult.success(serviceResult.getResult());
    }

    /**
     * 修改产品
     * @param productInfo
     */
    @ApiOperation(value = "修改产品信息")
    @PutMapping(value = "/update")
    public ResponseResult updateProduct(@RequestBody ProductInfo productInfo) {
        ServiceResult<Integer> serviceResult = productInfoService.updateProductInfo(productInfo);
        if(!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(), serviceResult.getMessage());
        }
        return ResponseResult.success();
    }

    /**
     * 创建产品。
     */
    @PostMapping(value = "/insert")
    public ResponseResult createProduct(@RequestBody ProductInfo productInfo) {
        Long domainId = CloudApplicationContext.domainId.get();
        if(domainId == null) {
            return ResponseResult.error(DeviceExcpConstants.ERROR_CODE_LACK_PARAM, DeviceExcpConstants.ERROR_MSG_LACK_PARAM);
        }
        productInfo.setDomainId(domainId);
        ServiceResult<ProductInfo> serviceResult = productInfoService.createProductInfo(productInfo);
        if(!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(), serviceResult.getMessage());
        }

        return ResponseResult.success(serviceResult.getResult());
    }

    /**
     * 修改产品转发地址
     * @return
     */
    @RequestMapping(value = "updateRedirect", method = { RequestMethod.POST,RequestMethod.PUT })
    public ResponseResult updateRedirect(@RequestBody Map<String,String> params) {
        ParamUtil.checkParams(params,"subDomainId");
        Long subDomainId = Long.valueOf(params.get("subDomainId"));
        String serviceId = params.get("serviceId");
        if (serviceId != null && !serviceId.isEmpty()){
            // 数据转发 uds + 平台
            ProductInfo productInfo = new ProductInfo();
            productInfo.setDomainId(CloudApplicationContext.domainId.get());
            productInfo.setSubDomainId(subDomainId);
            productInfo.setServiceId(Long.valueOf(serviceId));
            //调用server服务，获取uds服务信息
            ResponseResult responseResult = serverFeignApi.getUdsService(Long.valueOf(serviceId));
            if(!responseResult.isSuccess()) {
                log.error("get user service error：" + responseResult.getMessage());
                return ResponseResult.error(responseResult.getCode(),responseResult.getMessage());
            }
            JSONObject udsServiceInfo = JSONObject.parseObject(JSON.toJSONString(responseResult.getResult()));
            String serviceIp = udsServiceInfo.getString("serviceIp");
            Integer servicePort = udsServiceInfo.getInteger("servicePort");
            log.info("get product info:" + JSONObject.toJSONString(productInfo));
            ServiceResult<Integer> serviceResult = productInfoService.updateProductInfoAndApi(productInfo, serviceIp, servicePort);
            if (!serviceResult.getSuccess()) {
                log.error("update product info error:" + serviceResult.getMessage());
                return ResponseResult.error(serviceResult.getCode(),serviceResult.getMessage());
            }
            String dataUrl = serviceIp + ":" + servicePort + "/dataReport";
            String statusUrl = serviceIp + ":" + servicePort + "/statusReport";
            //更新UDS服务信息
            serverFeignApi.updateUdsRedirectUrl(Long.valueOf(serviceId),dataUrl,statusUrl);
            return ResponseResult.success(serviceResult.getResult());
        }else {
            // 设置设备数据转发到平台
            JSONObject result = new JSONObject();
            String setDataResult = productInfoService.setPlatformDataReportServer(CloudApplicationContext.domainId.get(), subDomainId);
            result.put("setDataResult",setDataResult);
            // 设置设备状态转发到平台
            String setStatusResult = productInfoService.setPlatformStatusReportServer(CloudApplicationContext.domainId.get(), subDomainId);
            result.put("setStatusResult",setStatusResult);
            return ResponseResult.success(result);
        }
    }

    /**
     * 产品转发地址回显
     * @param subDomainId
     * @return
     */
    @RequestMapping(value = "/forward/{subDomainId}", method = { RequestMethod.GET })
    public ResponseResult goBackRedirect(@PathVariable("subDomainId") Long subDomainId) {
        ServiceResult<ProductInfo> serviceResult = productInfoService.getProductInfoById(String.valueOf(subDomainId));
        if(!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(),serviceResult.getMessage());
        }
        ProductInfo productInfo = serviceResult.getResult();
        return ResponseResult.success(productInfo.getServiceId());
    }

    /**
     * 获取产品转发地址
     * @param subDomainId
     * @return
     */
    @RequestMapping(value = "/redirect/{subDomainId}", method = { RequestMethod.GET })
    public ResponseResult getRedirectInfo(@PathVariable("subDomainId") Long subDomainId) {
        ServiceResult<Long> serviceResult = productInfoService.getRedirectInfo(subDomainId);
        if (!serviceResult.getSuccess()) {
            log.error("get product redirect address error:" + serviceResult.getMessage());
            return ResponseResult.error(serviceResult.getCode(),serviceResult.getMessage());
        }
        return ResponseResult.success(serviceResult.getResult());
    }

}
